$(document).ready(function() {
	$('.charges-editing').each(function() {
		container = $(this);
		function t(selector) { return $(selector, container); }
		
		t(':button.add-record').click(function() {
			copy_form_fields(t('.add-form-row'), t('.add-form-table'));
			t('.add-form').submit();
		});
		
		// Bind bind 'change' button click event.
		t(':button.change-record').click(function() {
			edit_record($(this).parents('tr:first'));
		});
		
		// Bind row double click event. Same action that a 'change' button click.
		t('.data-row').dblclick(function() {
			edit_record($(this));
		});
	});
});


/**
 * Update row events after saving changes.
 */
function update_row_events(row) {
	$(':button.change-record', row).click(function() {
		edit_record(row);
	});
	
	row.dblclick(function() {
		edit_record(row);
	});
}


/**
 * Make table row editable.
 */
function edit_record(row) {
	var container = row.parents('.charges-editing:first');
	
	row.children('.editable').each(function(index, element) {
		var fields = $('.add-form-row', container).children('.editable');
		var value = $(this).text().replace(/^\s+|\s+$/g, '');
		$(this).html(fields.eq(index).html());
		$(this).children('input').val(value);
		
		var btn = $(':button', row);
		btn.val('save');
		// Define save action.
		btn.attr('class', 'save-record warning-button');
		btn.unbind('click');
		row.unbind('dblclick');
		btn.click(function() {
			save_record($(this).parents('tr:first'));
		});
	});
}


/**
 * Send request for saving record.
 */
function save_record(row) {
	var container = row.parents('.charges-editing:first');
	copy_form_fields(row, $('.save-form-table', container));
	$('.save-form', container).ajaxSubmit(function(response) {
		row.html(response);
		update_row_events(row);
	});
}


/**
 * Clone html form.
 */
function copy_form_fields(src, dst) {
	var html = '';
	// Don't know how fix it but works fine. Looks simple but don't work otherwise.
	$('input', src).each(function() {
		html += '<input name="' + $(this).attr('name') + '" value="' + $(this).val() + '"/>';
	});
	
	$('select', src).each(function() {
		html += '<input name="' + $(this).attr('name') + '" value="' + $(this).val() + '"/>';
	});
	
	dst.html(html);
}
